package com.leyou.item.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.item.Mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品分类Service
 */
@Service
@Transactional
public class CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    /**
     * 1.封装条件
     *
     *Wrappers.query():无参方法，一般是用在单表中比较复杂的查询
     * Wrappers.query(T):有参方法，一般是用在单表中比较简单的查询（如指定字段查询）
     * @param pid
     * @return
     */
    public List<Category> findCategoriesByPid(Long pid) {

        Category category = new Category();
        category.setParentId(pid);

        QueryWrapper<Category> wrapper = Wrappers.query(category);

        //2.执行查询，获取结果
        List<Category> categories = categoryMapper.selectList(wrapper);

        //3.处理结果并返回
        if(CollectionUtils.isEmpty(categories)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return categories;
    }

    //selectBatchIds：根据ids集合批量查找分类集合，返回分类集合
    public List<Category> findCategoriesByIds(List<Long> ids) {
        List<Category> categories = categoryMapper.selectBatchIds(ids);
        if(CollectionUtils.isEmpty(categories)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return categories;
    }


    public List<Object> categoryListById(Long pid) {
        Map<String,Object>  map1 = new HashMap<>();
        List<Object> names1 = new ArrayList<>(); // 最外层list

        // 一级分类列表
        List<Category> categoriesByPid1 = findCategoriesByPid(pid);
        // 遍历得到所有的顶级分类列表的名字和id，顶级分类的id就是中级分类的父id
        for (Category category1 : categoriesByPid1) {
            // 二级分类列表
            List<Category> categoriesByPid2 = findCategoriesByPid(category1.getId());

            List<Object> names2 = new ArrayList<>();
            for (Category category2 : categoriesByPid2) {
                Map<String,Object>  map2 = new HashMap<>();
                // 三级分类列表
                List<Category> categoriesByPid3 = findCategoriesByPid(category2.getId());
                // List<map1<String,list<map2<String,list<Category>>>>>
                map2.put(category2.getName(),categoriesByPid3);
                names2.add(map2);
            }
            map1.put(category1.getName(),names2);
        }
        names1.add(map1);
        return names1;
    }
}
